package May._06.test29;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;


import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Student[] students = new Student[10];
        //输入Students信息
        inputStudent(students);
        //取出null
        int length = students.length;
        Student[] realStudents = new Student[length];
        for (int i = 0; i < 10; i++) {
            if(students[i]!=null){
                realStudents[i]=students[i];
            }
        }

        //排序
        Arrays.sort(realStudents, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.age-o2.age;
            }
        });

        //写入文件
        OutputStreamWriter out=null;
        try {
             out = new OutputStreamWriter(new FileOutputStream("fileTest\\a.txt",true));
            for (int i = 0; i < length; i++) {
                String id = String.valueOf(realStudents[i].id);
                String age = String.valueOf(realStudents[i].age);
                String str = "id=" + id + " name=" + realStudents[i].name + " age=" + age;
                out.write(str);
                out.write(System.lineSeparator());
                out.flush();
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    private static void inputStudent(Student[] students) {
        Scanner scanner = new Scanner(System.in);
        for (int i = 0; i < 10; i++) {
            String msg = scanner.nextLine();
            if ("exit".equals(msg)){
                break;
            }
            String[] split = msg.split(" ");
            int id = Integer.parseInt(split[0]);
            int age = Integer.parseInt(split[2]);
            Student student = new Student(id, split[1], age);
            students[i]=student;
        }
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
class Student{
    int id;
    String name;
    int age;
}
